from fileinput import filename
from fastapi import APIRouter, Depends, File, UploadFile, FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from typing import Callable, Union
from core.response import response_code
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session
from typing import List
from setting.web import settings
from db.minio import minio_client
from io import BytesIO
from common.deps import check_jwt_token, get_db
from common.utils import build_file_path,text_to_ascii
from minio.commonconfig import Tags
import crud
import uuid

router = APIRouter()


@router.post("/upload", summary="单个文件上传", description='文件大小不能超过10M 限制文件格式为图片'
)
async def create_upload_file(file: UploadFile = File(...), db: Session = Depends(get_db)):
    contents = await file.read()
    # 判断文件后缀是否符合要求
    if file.filename.split(".")[-1] not in settings.ALLOWED_EXTENSIONS:
        return response_code.resp_500(message="File extension not allowed")

    # 检查文件大小
    if len(contents) > settings.MAX_UPLOAD_SIZE:
        #raise HTTPException(detail="File too large")
        return response_code.resp_500(message="File too large")
    file_id, file_path, file_path_with_no_prefix = build_file_path(
        file.filename, 'events')
    with open(file_path, 'wb') as f:
        f.write(contents)
        f.close()
    #crud.event_img.create_event_image(db, file_id, file_path_with_no_prefix)
    return response_code.resp_200(data={"fileId": file_id, "filePath": file_path_with_no_prefix})


@router.post("/uploads", summary="多个文件上传", description='文件大小不能超过10M 限制文件格式为图片')
async def create_upload_files(files: List[UploadFile] = File(...), db: Session = Depends(get_db)):
    file_ids = []
    for file in files:
        contents = await file.read()
        # 判断文件后缀是否符合要求
        if file.filename.split(".")[-1] not in settings.ALLOWED_EXTENSIONS:
            return response_code.resp_500(message="File extension not allowed")
        # 检查文件大小
        if len(contents) > settings.MAX_UPLOAD_SIZE:
            return response_code.resp_500(message="File too large")

        file_id, file_path, file_path_with_no_prefix = build_file_path(
            file.filename, 'events')
        file_ids.append(file_id)
        with open(file_path, 'wb') as f:
            f.write(contents)
            f.close()

        #crud.event_img.create_event_image(
        #    db, file_id, file_path_with_no_prefix)
    return response_code.resp_200(data={"file_ids": file_ids})


@router.post("/avatarUpload", summary="头像上传", description='文件大小不能超过10M 限制文件格式为图片')
async def upload_avatar_file(file: UploadFile = File(...), db: Session = Depends(get_db),payload=Depends(check_jwt_token)):
    uid = payload.get("uid")
        #return res.to_dict()
    contents = await file.read()
    # 判断文件后缀是否符合要求
    if file.filename.split(".")[-1] not in settings.ALLOWED_EXTENSIONS:
        return response_code.resp_500(message="File extension not allowed")
    # 检查文件大小
    if len(contents) > settings.MAX_UPLOAD_SIZE:
        #raise HTTPException(detail="File too large")
        return response_code.resp_500(message="File too large")
    avatar_id = str(uuid.uuid4())+'.jpg'
    #file_id, file_path, file_path_with_no_prefix = build_file_path(
    #    file.filename.split(".")[-1],'avatar')
    file_obj = BytesIO(contents)
    minio_client.put_object('avatar',avatar_id,file_obj,len(contents))
    #with open(file_path, 'wb') as f:
    #    f.write(contents)
    #    f.close()
    crud.user.update_avator(db,uid,avatar_id)
    return response_code.resp_200(data={})

@router.post("/registerUserFace", summary="人脸注册", description='文件大小不能超过10M 限制文件格式为图片')
async def register_face(id:int,file: UploadFile = File(...), db: Session = Depends(get_db),payload=Depends(check_jwt_token)):
    # uid = payload.get("uid")
        #return res.to_dict()
    res = crud.user.get_user_by_uid(db,id)
    bucket_name = 'face'
    contents = await file.read()
    # 判断文件后缀是否符合要求
    if file.filename.split(".")[-1] not in settings.ALLOWED_EXTENSIONS:
        return response_code.resp_500(message="File extension not allowed")
    # 检查文件大小
    if len(contents) > settings.MAX_UPLOAD_SIZE:
        #raise HTTPException(detail="File too large")
        return response_code.resp_500(message="File too large")
    avatar_id = str(uuid.uuid4())+'.jpg'
    #file_id, file_path, file_path_with_no_prefix = build_file_path(
    #    file.filename.split(".")[-1],'avatar')
    file_obj = BytesIO(contents)
    tags = Tags(for_object=True)
    tags['id'] = str(id)
    tags['name'] = text_to_ascii(res.name)
    minio_client.put_object(bucket_name,avatar_id,file_obj,len(contents),tags=tags)
    return response_code.resp_200(data={'name':avatar_id,'bucket': bucket_name})

@router.get("/getUserFaces", summary="获取人脸", description='无')
async def register_face(id:str,db: Session = Depends(get_db),payload=Depends(check_jwt_token)):
    result = []
    tag_key = 'id'
    tag_value = id
    bucket_name = 'face'
    #try:
        # 列出存储桶中的所有对象
    objects = minio_client.list_objects(bucket_name)
    for obj in objects:
        # 获取对象的标签
        tags = minio_client.get_object_tags(bucket_name, obj.object_name)
        if tags == None:
            continue
        # 检查标签是否符合条件
        if tags.get(tag_key) == tag_value:
            file_url = minio_client.presigned_get_object(bucket_name, obj.object_name)
            result.append({
                "name": obj.object_name,
                "url": file_url,
                'bucket': bucket_name
            })
    return response_code.resp_200(data= result)
    
@router.delete("/{bucket}/{filename}")
async def delete_file(bucket:str,filename: str):
    # 删除文件
    minio_client.remove_object(bucket, filename)
    return response_code.resp_200(data= {})
    

@router.get("/avatar/{file_name}")
async def get_avatar(file_name: str):
    try:
        # 假设头像的文件名是 user_id.jpg
        # file_name = f"{user_id}.jpg"
        
        # 检查 MinIO 中是否存在该头像
        if not minio_client.bucket_exists('avatar'):
            raise HTTPException(status_code=404, detail="Bucket not found")

        # 获取头像文件
        try:
            file_obj = minio_client.get_object('avatar', file_name)
        except Exception as e:
            raise HTTPException(status_code=404, detail="Avatar not found")
        
        # 将 MinIO 文件流返回给客户端
        return StreamingResponse(file_obj, media_type="image/jpeg")

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/face/{file_name}")
async def get_face(file_name: str):
    try:
        # 假设头像的文件名是 user_id.jpg
        # file_name = f"{user_id}.jpg"
        
        # 检查 MinIO 中是否存在该头像
        if not minio_client.bucket_exists('face'):
            raise HTTPException(status_code=404, detail="Bucket not found")

        # 获取头像文件
        try:
            file_obj = minio_client.get_object('face', file_name)
        except Exception as e:
            raise HTTPException(status_code=404, detail="Avatar not found")
        
        # 将 MinIO 文件流返回给客户端
        return StreamingResponse(file_obj, media_type="image/jpeg")

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))